package com.cse.utils;

import cn.hutool.core.lang.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
public class SimpleRedisLock implements  ILock{
    private final StringRedisTemplate stringRedisTemplated;
    private String name;

    //用构造函数接收上面两个参数
    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplated) {
        this.stringRedisTemplated = stringRedisTemplated;
        this.name = name;
    }
    private static final String KEY_PREFIX="lock:";
    private static final String ID_PREFIX= UUID.randomUUID().toString(true);
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        //在静态代码块理初始化脚本
        UNLOCK_SCRIPT=new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }
    @Override
    public boolean tryLock(long timeoutSec) {
        //setIfAbsent()->不存在才执行
        String threadid = ID_PREFIX+Thread.currentThread().getId();
        Boolean success = stringRedisTemplated.opsForValue().setIfAbsent
                (KEY_PREFIX + name, threadid , timeoutSec, TimeUnit.SECONDS);
        //直接调用sucess会自动拆箱可能会引发空指针（ if sucess为null)
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unlock() {
       //调用lua脚本
        stringRedisTemplated.execute(UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX+name),
                ID_PREFIX+Thread.currentThread().getId());
    }
}
